using UnityEngine;
using System.Collections;

[USequencerEvent("Fullscreen/Fade Screen")]
public class USFadeScreenEvent : USEventBase 
{
	public AnimationCurve fadeCurve = new AnimationCurve(new Keyframe(0.0f, 0.0f), new Keyframe(1.0f, 1.0f), new Keyframe(3.0f, 1.0f), new Keyframe(4.0f, 0.0f));
	public Color fadeColour = Color.black;
	
	private float currentCurveSampleTime = 0.0f;
	public Texture2D texture = null;
	
	private GUITexture GetGUITexture()
	{
		if(!AffectedObject.GetComponent<GUITexture>())
		{
			Debug.LogWarning("You used a USFadeScreen Event on an object without a GUITexture, we've added one for you. This means we will have to reset the transform.");
			AffectedObject.AddComponent<GUITexture>();
		}
		
		AffectedObject.transform.position = Vector3.zero;
		AffectedObject.transform.rotation = Quaternion.identity;
		
		return AffectedObject.GetComponent<GUITexture>();
	}
	
	public override void FireEvent()
	{
		
	}
	
	public override void ProcessEvent(float deltaTime)
	{		
		currentCurveSampleTime = deltaTime;
		
		GUITexture guiTexture = GetGUITexture();
		if(!guiTexture.texture)
			guiTexture.texture = new Texture2D(1, 1, TextureFormat.ARGB32, false);
		
		guiTexture.pixelInset = new Rect(0, 0, Screen.width, Screen.height);
		guiTexture.transform.localScale = Vector3.one;
		
		float alpha = fadeCurve.Evaluate(currentCurveSampleTime);
		
		alpha = Mathf.Min(Mathf.Max(0.0f, alpha), 1.0f);
		
		if(texture == null)
			texture = new Texture2D(1, 1, TextureFormat.ARGB32, false);
		
    	texture.SetPixel(0, 0, new Color(fadeColour.r, fadeColour.g, fadeColour.b, alpha));
		texture.Apply();
		
		guiTexture.texture = texture;
	}
	
	public override void EndEvent()
	{	
		
	}
	
	public override void UndoEvent()
	{	
		currentCurveSampleTime = 0.0f;
	}
	
	void OnGUI()
	{	
		float maxTime = 0.0f;
		foreach(Keyframe key in fadeCurve.keys)
		{
			if(key.time > maxTime)
				maxTime = key.time;
		}
		
		Duration = maxTime;
	}
	
	void OnEnable()
	{
		if(texture == null)
			texture = new Texture2D(1, 1, TextureFormat.ARGB32, false);
		
    	texture.SetPixel(0, 0, new Color(fadeColour.r, fadeColour.g, fadeColour.b, 1.0f));
		texture.Apply();	
	}
}
